//
//  SHSessionInteractorImpl.m
//  Netease
//
//  Created by 王方伟 on 2017/12/22.
//  Copyright © 2017年 wfw. All rights reserved.
//

#import "SHSessionInteractorImpl.h"
#import "NTESMediaPreviewViewController.h"
#import "NIMLocationViewController.h"
#import "NTESFilePreViewController.h"
#import "NIMKitFileLocationHelper.h"
#import "NTESVideoViewController.h"
#import "HVideoViewController.h"
#import "NIMKitLocationPoint.h"
#import "SHChooseAlbumTool.h"
#import "SHKitMediaFetcher.h"
#import "NIMMessageMaker.h"
#import "SHPhotoBrowser.h"

@interface SHSessionInteractorImpl ()<PhotoBrowserDelegate>
@property (nonatomic,strong) SHKitMediaFetcher *mediaFetcher;
@property (nonatomic,strong) NIMSession  *session;
@property (strong, nonatomic) NSArray *messages;
@property (strong, nonatomic) UIView *touchView;
@end



@implementation SHSessionInteractorImpl

- (instancetype)initWithSession:(NIMSession *)session config:(id<NIMSessionConfig>)sessionConfig{
    self = [super initWithSession:session config:sessionConfig];
    if (self) {
        _session = session;
    }
    return self;
}

#pragma mark 选择相册
- (void)mediaPicturePressed{
    __weak typeof(self) weakSelf = self;
    [self.mediaFetcher fetchPhotoFromLibrary:^(NSArray *images, NSString *path, PHAssetMediaType type) {
        switch (type) {
            case PHAssetMediaTypeImage:{
                for (UIImage *image in images) {
                    NIMMessage *message = [NIMMessageMaker msgWithImage:image];
                    [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:weakSelf.session error:nil];
                }
                if (path) {
                    NIMMessage *message;
                    if ([path.pathExtension isEqualToString:@"HEIC"]){
                        //iOS 11 苹果采用了新的图片格式 HEIC ，如果采用原图会导致其他设备的兼容问题，在上层做好格式的兼容转换,压成 jpeg
                        UIImage *image = [UIImage imageWithContentsOfFile:path];
                        message = [NIMMessageMaker msgWithImage:image];
                    }else{
                        message = [NIMMessageMaker msgWithImagePath:path];
                    }
                    [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:weakSelf.session error:nil];
                }
            }
                break;
            case PHAssetMediaTypeVideo:{
                NIMMessage *message = [NIMMessageMaker msgWithVideo:path];
                [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:weakSelf.session error:nil];
            }
                break;
            default:
                return;
        }
        
    }];
}

#pragma mark 选择拍摄
- (void)mediaShootPressed:(NIMSession *)session{
    HVideoViewController *video = [[NSBundle mainBundle] loadNibNamed:@"HVideoViewController" owner:nil options:nil].lastObject;
    video.HSeconds = 15;
    video.takeBlock = ^(id item) {
        NIMMessage *message;
        if ([item isKindOfClass:[UIImage class]]) {
            message = [NIMMessageMaker msgWithImage:item];
        }else{
            message = [NIMMessageMaker msgWithVideo:item];
        }
        [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
    };
    [DCURLRouter presentViewController:video animated:YES completion:nil];
}

#pragma mark 查看地理位置
- (void)showLocation:(NIMMessage *)message{
    NIMLocationObject *object = message.messageObject;
    NIMKitLocationPoint *locationPoint = [[NIMKitLocationPoint alloc] initWithLocationObject:object];
    NIMLocationViewController *vc = [[NIMLocationViewController alloc] initWithLocationPoint:locationPoint];
    [DCURLRouter pushViewController:vc animated:YES];
}

#pragma mark 查看视频
- (void)showVideo:(NIMMessage *)message session:(NIMSession *)session{
    NIMVideoObject *object = message.messageObject;
    NTESVideoViewItem *item = [[NTESVideoViewItem alloc] init];
    item.path = object.path;
    item.url  = object.url;
    item.session = session;
    item.itemId  = object.message.messageId;
    
    NTESVideoViewController *playerViewController = [[NTESVideoViewController alloc] initWithVideoViewItem:item];
    [DCURLRouter pushViewController:playerViewController animated:YES];
    if(![[NSFileManager defaultManager] fileExistsAtPath:object.coverPath]){
        //如果封面图下跪了，点进视频的时候再去下一把封面图
        __weak typeof(self) weakSelf = self;
        [[NIMSDK sharedSDK].resourceManager download:object.coverUrl filepath:object.coverPath progress:nil completion:^(NSError *error) {
            if (!error) {
                [weakSelf updateMessage:message];
            }
        }];
    }
}

#pragma mark 查看文件
- (void)showFile:(NIMMessage *)message{
    NIMFileObject *object = message.messageObject;
    NTESFilePreViewController *vc = [[NTESFilePreViewController alloc] initWithFileObject:object];
    [DCURLRouter pushViewController:vc animated:YES];
}

#pragma mark 查看图片
- (void)showImage:(NIMMessage *)message session:(NIMSession *)session{
    _touchView = message.localExt[@"touchView"];
    NIMMessageSearchOption *option = [[NIMMessageSearchOption alloc] init];
    option.limit = 0;
    option.messageTypes = @[@(NIMMessageTypeImage)];
    __weak typeof(self) weakSelf = self;
    [[NIMSDK sharedSDK].conversationManager searchMessages:session option:option result:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
        weakSelf.messages = messages;
        
        NSInteger index = [messages indexOfObject:message];
        [SHPhotoBrowser show:[[DCURLRouter sharedDCURLRouter] currentViewController] delegate:self index:index configBlock:^(PhotoBrowserConfig *config) {
//            config.isShowMoreButton = YES;
            config.moreNormalImage = [UIImage imageNamed:@"icon_gallery_more_normal"];
            config.morePressedImage = [UIImage imageNamed:@"icon_gallery_more_pressed"];
        }];
    }];
}


#pragma mark PhoteBrowser 代理
#pragma mark 一个都多少张图片
- (NSInteger)numberOfPhotos:(SHPhotoBrowser *)photoBrowser{
    return _messages.count;
}

#pragma mark 站位图片
- (UIImage *)photoBrowser:(SHPhotoBrowser *)photoBrowser index:(NSInteger)index{
    NIMMessage *message = _messages[index];
    NIMImageObject *object = message.messageObject;
    if(![[NSFileManager defaultManager] fileExistsAtPath:object.thumbPath]){
        //如果缩略图下跪了，点进看大图的时候再去下一把缩略图
        __weak typeof(self) weakSelf = self;
        [[NIMSDK sharedSDK].resourceManager download:object.thumbUrl filepath:object.thumbPath progress:nil completion:^(NSError *error) {
            if (!error) {
                [weakSelf updateMessage:message];
            }
        }];
    }
    
    return [UIImage imageNamed:[object thumbPath]];
}

#pragma mark 从哪个视图开始展示
- (UIView *)photoBrowser:(SHPhotoBrowser *)photoBrowser showViewIndex:(NSInteger)index{
    return _touchView;
}

#pragma mark 网络图片地址
- (NSURL *)photoBrowser:(SHPhotoBrowser *)photoBrowser highQualityUrlIndex:(NSInteger)index{
    NIMMessage *message = _messages[index];
    NIMImageObject *object = message.messageObject;
    return [NSURL URLWithString:[object url]];
}

#pragma mark 查看更多图片
- (void)onTouchMore:(SHPhotoBrowser *)photoBrowser{
    
    NSMutableArray *objects = [[NSMutableArray alloc] init];
    
    //显示的时候新的在前老的在后，逆序排列
    //如果需要微信的显示顺序，则直接将这段代码去掉即可
    NSArray *array = self.messages.reverseObjectEnumerator.allObjects;
    
    for (NIMMessage *message in array){
        switch (message.messageType) {
            case NIMMessageTypeVideo:{
                NTESMediaPreviewObject *object = [self previewObjectByVideo:message.messageObject];
                [objects addObject:object];
                break;
            }
            case NIMMessageTypeImage:{
                NTESMediaPreviewObject *object = [self previewObjectByImage:message.messageObject];
                [objects addObject:object];
                break;
            }
            default:
                break;
        }
    }
    NTESMediaPreviewViewController *vc = [[NTESMediaPreviewViewController alloc] initWithPriviewObjects:objects focusObject:nil];
    [DCURLRouter pushViewController:vc animated:YES];
}

#pragma mark 长按图片
- (void)photoBrowser:(SHPhotoBrowser *)photoBrowser didLongPressIndex:(NSInteger)index image:(UIImage *)image{
    [[SHChooseAlbumTool sharedChooseAlbum] longPanSaveImageToAlbum:image];
}


- (NTESMediaPreviewObject *)previewObjectByVideo:(NIMVideoObject *)object{
    NTESMediaPreviewObject *previewObject = [[NTESMediaPreviewObject alloc] init];
    previewObject.objectId  = object.message.messageId;
    previewObject.thumbPath = object.coverPath;
    previewObject.thumbUrl  = object.coverUrl;
    previewObject.path      = object.path;
    previewObject.url       = object.url;
    previewObject.type      = NTESMediaPreviewTypeVideo;
    previewObject.timestamp = object.message.timestamp;
    previewObject.displayName = object.displayName;
    previewObject.duration  = object.duration;
    previewObject.imageSize = object.coverSize;
    return previewObject;
}

- (NTESMediaPreviewObject *)previewObjectByImage:(NIMImageObject *)object{
    NTESMediaPreviewObject *previewObject = [[NTESMediaPreviewObject alloc] init];
    previewObject.objectId = object.message.messageId;
    previewObject.thumbPath = object.thumbPath;
    previewObject.thumbUrl  = object.thumbUrl;
    previewObject.path      = object.path;
    previewObject.url       = object.url;
    previewObject.type      = NTESMediaPreviewTypeImage;
    previewObject.timestamp = object.message.timestamp;
    previewObject.displayName = object.displayName;
    previewObject.imageSize = object.size;
    return previewObject;
}


#pragma mark - Private
- (SHKitMediaFetcher *)mediaFetcher{
    if (!_mediaFetcher) {
        _mediaFetcher = [[SHKitMediaFetcher alloc] init];
    }
    return _mediaFetcher;
}
@end
